//
//  HLCourseDetailViewController.m
//  HLAerospace
//
//  Created by hulian-ios on 17/9/8.
//  Copyright © 2017年 hulian-LB. All rights reserved.
//

#import "HLCourseDetailViewController.h"
#import <ZFPlayer/ZFPlayer.h>
#import <Masonry/Masonry.h>
#import <MJExtension/MJExtension.h>
#import "HLDetaiVideoRecommandView.h"
#import "HLDetailNodeView.h"
#import "HLDetailDiscussView.h"
#import "HLStartQusetionViewController.h"
#import "HLCourseDiscuss.h"
#import "HLCommentListController.h"
#import "HLFoldCourse.h"
#import "HttpRequestManager.h"
#import "HLUserInfo.h"
#import "MBProgressHUD+HL.h"
#import "HLCourseDetail.h"
#import "HLCreateNoteController.h"
#import "HLPlaceHolderTextView.h"
#import "HLDataBaseManager.h"
#import "HLCollect.h"
#import "HLMoreCourse.h"
#import "HLDownLoaderManager.h"

#define kTabBarViewHeight (IS_IPHONE_5 ? 50 : 60)
#define kVideoViewHeight (ScreenWidth * 9.0f/16.0f)

typedef NS_ENUM(NSUInteger, HLBottomButtonType) {
    HLBottomButtonTypeBack,
    HLBottomButtonTypeCollect,
    HLBottomButtonTypeDownload
};

@interface HLCourseDetailViewController ()<UIScrollViewDelegate,ZFPlayerDelegate,HLDetailDiscussViewDelegate,HLDetailNodeViewDelegate>
{
    UIButton *_currentSelectedTabBarButton;
}
@property (nonatomic ,strong) UIScrollView *contentScrollView;
@property (nonatomic ,strong) NSMutableArray *tabBarButtons;
@property (nonatomic ,strong) NSMutableArray *bottomButtons;

/********************** 视频相关 ************************/
@property (strong, nonatomic) UIView *playerFatherView;
@property (strong, nonatomic) ZFPlayerView *playerView;
@property (strong, nonatomic) ZFPlayerModel *playerModel;
/** 离开页面时候是否在播放 */
@property (nonatomic, assign) BOOL isPlaying;
@property (strong, nonatomic) HLDetailDiscussView *discussView;

@end

@implementation HLCourseDetailViewController

#pragma mark - Lazy

- (NSMutableArray *)tabBarButtons
{
    if (!_tabBarButtons ) {
        _tabBarButtons = [NSMutableArray array];
    }
    return _tabBarButtons;
}

- (NSMutableArray *)bottomButtons
{
    if (!_bottomButtons ) {
        _bottomButtons = [NSMutableArray array];
    }
    return _bottomButtons;
}

- (ZFPlayerModel *)playerModel {
    if (!_playerModel) {
        _playerModel = [[ZFPlayerModel alloc] init];
        _playerModel.title  = self.courseDetail.name;
        _playerModel.videoURL =  [NSURL URLWithString:self.courseDetail.play_url];
        _playerModel.placeholderImage = [UIImage imageNamed:@"loading_bgView1"];
        _playerModel.fatherView = self.playerFatherView;
    }
    return _playerModel;
}

- (ZFPlayerView *)playerView {
    if (!_playerView) {
        _playerView = [[ZFPlayerView alloc] init];
        [_playerView playerControlView:nil playerModel:self.playerModel];
        _playerView.delegate = self;
        self.playerView.hasPreviewView = YES;
    }
    return _playerView;
}

- (UIScrollView *)contentScrollView
{
      if (!_contentScrollView) {
          CGFloat scrollViewHeight = ScreenHeight - 44 - kTabBarViewHeight - kVideoViewHeight - 20;
          UIScrollView *contentScrollView = [[UIScrollView alloc] init];
          contentScrollView.frame = CGRectMake(0, kTabBarViewHeight, ScreenWidth, scrollViewHeight);
          contentScrollView.contentSize = CGSizeMake(3 * ScreenWidth, 0);
          contentScrollView.backgroundColor = HLRGB(245, 245, 245);
          contentScrollView.showsVerticalScrollIndicator = NO;
          contentScrollView.showsHorizontalScrollIndicator = NO;
          contentScrollView.delegate = self;
          contentScrollView.pagingEnabled = YES;
          _contentScrollView = contentScrollView;
    }
    return _contentScrollView;
}

// 返回值要必须为NO
- (BOOL)shouldAutorotate
{
    return NO;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    
    /**** pop回来时候是否自动播放 ****/
    if (self.navigationController.viewControllers.count == 2  && self.isPlaying) {
        self.isPlaying = NO;
        self.playerView.playerPushedOrPresented = NO;
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
    
    /**** push出下一级页面时候暂停 ****/
    if (self.navigationController.viewControllers.count == 3 && self.playerView && !self.playerView.isPauseByUser)
    {
        self.isPlaying = YES;
        //        [self.playerView pause];
        self.playerView.playerPushedOrPresented = YES;
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setBottomView];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(userAskQuestionSuccess) name:kHLUserAskQuestionSuccessNotifacation object:nil];
    
    [self setPlayerFatherView];
    
    if (self.courseDetail.filePath && self.courseDetail.filePath.length > 0) {
        self.playerModel.videoURL = [NSURL fileURLWithPath:self.courseDetail.filePath];
        [self.playerView autoPlayTheVideo];
        [self setTabbarView];
        [self configBottomButton];
    }else{
        [self loadRequest];

    }
}

- (void)configReachableViaWiFiState
{
    BOOL isReachableViaWiFi =  [[AFNetworkReachabilityManager sharedManager] isReachableViaWiFi];
    if (isReachableViaWiFi) {
        [self.playerView autoPlayTheVideo];
    }else{
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"当前还没有连接WIFI,确定继续播放吗?"message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self.playerView autoPlayTheVideo];
        }]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            [self.playerView pause];
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}


- (void)setPlayerFatherView
{
    self.playerFatherView = [[UIView alloc] init];
    [self.view addSubview:self.playerFatherView];
    [self.playerFatherView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(20);
        make.leading.trailing.mas_equalTo(0);
        // 这里宽高比16：9,可自定义宽高比
        make.height.mas_equalTo(self.playerFatherView.mas_width).multipliedBy(9.0f/16.0f);
    }];
}

- (void)setTabbarView
{
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    UIView *tabBarView = [[UIView alloc] init];
    tabBarView.frame = CGRectMake(0, kVideoViewHeight + 20, ScreenWidth, ScreenHeight -( ScreenWidth * 9.0f/16.0f + 20)  - 44);
    tabBarView.backgroundColor = HLRGB(245, 245, 245);
    [self.view addSubview:tabBarView];
    
    UIView *tabBarHeadView = [[UIView alloc]init];
    tabBarHeadView.frame = CGRectMake(0, 0, ScreenWidth, kTabBarViewHeight);
    [tabBarView addSubview:tabBarHeadView];
    
    [self cinfigTabBarHeadView:tabBarHeadView];
    [self cinfigTabBarScrollView:tabBarView];
    
}

- (NSArray *)bottomImages
{
    return @[@"home_course_back",@"home_course_collect",@"home_course_download"];
}

- (void)setBottomView
{
    self.view.backgroundColor = [UIColor blackColor];
    UIView *bottmView = [[UIView alloc] init];
    bottmView.frame = CGRectMake(0, ScreenHeight - 44, ScreenWidth, 44);
    bottmView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bottmView];
    
    CGFloat buttonW = ScreenWidth *0.3334;
    for (int i = 0; i < 3; i++) {
        UIButton *button = [[UIButton alloc] init];
        button.tag = i;
        button.frame = CGRectMake(buttonW * i, 0, buttonW, 44);
        [button setImage:[UIImage imageNamed:[self bottomImages][i]] forState:UIControlStateNormal];
        [bottmView addSubview:button];
        [button addTarget:self action:@selector(bottomButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.bottomButtons addObject:button];
    }
}

- (void)cinfigTabBarHeadView:(UIView *)view
{
    NSArray *titles = @[@"视频",@"讨论",@"笔记"];
    CGFloat buttonW = ScreenWidth *0.333334;
    for (int i = 0; i < 3; i++) {
        UIButton *button = [[UIButton alloc] init];
        button.tag = i;
        button.frame = CGRectMake(buttonW * i, 0, buttonW, kTabBarViewHeight - 1);
        [button setTitle:titles[i] forState:UIControlStateNormal];
        [button setTitleColor:kColorMineBlueBG forState:UIControlStateSelected];
        [button setTitleColor:HLRGB(60, 60, 60) forState:UIControlStateNormal];
        [view addSubview:button];
        [button addTarget:self action:@selector(tabBarButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        if (i == 0 ) {
            [self tabBarButtonClick:button];
        }
        [self.tabBarButtons addObject:button];
    }
    UIView *line = [[UIView alloc] init];
    line.frame = CGRectMake(0, kTabBarViewHeight - 1, ScreenWidth, 1);
    line.backgroundColor = HLRGB(235, 235, 235);
    [view addSubview:line];
}

- (void)cinfigTabBarScrollView:(UIView *)view
{
    CGFloat scrollViewHeight = ScreenHeight - 44 - kTabBarViewHeight - kVideoViewHeight - 20;
    HLDetaiVideoRecommandView *recommandView = [[HLDetaiVideoRecommandView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, scrollViewHeight)];
    recommandView.courseDetail = self.courseDetail;
    recommandView.courseid = self.foldCourse.wkid;
    
    HLDetailDiscussView *discussView = [[HLDetailDiscussView alloc]initWithFrame:CGRectMake(ScreenWidth, 0, ScreenWidth, scrollViewHeight)];
    discussView.courseID = self.foldCourse.wkid;
    discussView.delegate = self;
    self.discussView = discussView;
    
    HLDetailNodeView *noteView = [[HLDetailNodeView alloc] initWithFrame:CGRectMake(2*ScreenWidth, 0, ScreenWidth, scrollViewHeight) courseID: self.foldCourse.wkid];
    noteView.delegate = self;
    
    [view addSubview:self.contentScrollView];
    [self.contentScrollView addSubview:recommandView];
    [self.contentScrollView addSubview:discussView];
    [self.contentScrollView addSubview:noteView];
}

- (void)configBottomButton
{
    UIButton *collecteButton = self.bottomButtons[1];
    if ([self.courseDetail.state isEqualToString:@"1"]) {
         [collecteButton setImage:[UIImage imageNamed:@"home_course_collect_click"] forState:UIControlStateNormal];
    }
}

#pragma mark - Request
- (void)loadRequest
{
    [MBProgressHUD show];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"course_id"] = self.foldCourse.wkid;
    params[@"user_id"] = [HLUserInfo account].userid;
    params[@"sign"] = [kHLRequestGetCourseDetail signStr];
    __weak typeof(self) weakSelf = self;
    [[HTTPRequestManager defaultManager] HTTPGetRequestWithApiName:kHLRequestGetCourseDetail parameters:params success:^(NSURLSessionDataTask * _Nonnull dataTask, id  _Nonnull responseObject){
        [MBProgressHUD hideHUD];
        if ([responseObject[@"code"] integerValue] == 200) {
            weakSelf.courseDetail = [HLCourseDetail mj_objectWithKeyValues:responseObject[@"data"]];
            
            weakSelf.playerModel.videoURL = [NSURL URLWithString:weakSelf.courseDetail.play_url];
            [weakSelf configReachableViaWiFiState];
            
            [weakSelf setTabbarView];
            [weakSelf configBottomButton];
            
            /**** 加入历史记录 ****/
            if(!self.isSkipFormHistoryRecord){
                [weakSelf addCourseToDataBase];
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nonnull dataTask, NSError * _Nonnull error) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showErrorMessage:@"网络超时"];
    }];
}

- (void)addCourseToDataBase
{
    HLCollect *colecte = [HLCollect new];
    colecte.course_pic = self.moreCourse.pic.length == 0 ? self.history_record_pic_url:self.moreCourse.pic;
    colecte.course_name = self.courseDetail.name;
    colecte.course_type = @"1";
    colecte.father = self.moreCourse.name;
    colecte.num = self.courseDetail.num;
    colecte.course_id = self.courseDetail.ID;
    
    if ([HLDataBaseManager isHistoryRecord:colecte]) {
        [HLDataBaseManager removeHistoryRecord:colecte];
        [HLDataBaseManager addHistoryRecord:colecte];
    }else{
        [HLDataBaseManager addHistoryRecord:colecte];
    }
}

/**** 收藏 请求 ****/
- (void)collectedWith:(UIButton *)button
{
    [MBProgressHUD show];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"course_id"] = self.foldCourse.wkid;
    params[@"user_id"] = [HLUserInfo account].userid;
    params[@"sign"] = [kHLRequestFavourate signStr];
    params[@"type"] = [self.courseDetail.state isEqualToString:@"0"] ? @"1" : @"0";
    __weak typeof(self) weakSelf = self;
    [[HTTPRequestManager defaultManager] HTTPGetRequestWithApiName:kHLRequestFavourate parameters:params success:^(NSURLSessionDataTask * _Nonnull dataTask, id  _Nonnull responseObject){
        [MBProgressHUD hideHUD];
        if ([responseObject[@"code"] integerValue] == 200) {
            weakSelf.courseDetail.state = responseObject[@"sc_state"];
    
            [MBProgressHUD showSuccessMessage:([weakSelf.courseDetail.state isEqualToString:@"0"] ? @"取消收藏":@"收藏成功")];
            [button setImage:[UIImage imageNamed:([weakSelf.courseDetail.state isEqualToString:@"0"] ? @"home_course_collect":@"home_course_collect_click")] forState:UIControlStateNormal];
        }
        
    } failure:^(NSURLSessionDataTask * _Nonnull dataTask, NSError * _Nonnull error) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showErrorMessage:@"网络超时"];
    }];
}

/**** 删除笔记 请求 ****/
- (void)requestDeleteNote:(NSString *)note detailNodeView:(HLDetailNodeView *)detailNodeView
{
    [MBProgressHUD show];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"sign"] = [kHLRequestEditNotes signStr];
    params[@"course_id"] = self.foldCourse.wkid;
    params[@"type"] = @"0";
    params[@"content"] = note;
    params[@"user_id"] = [HLUserInfo account].userid;
    [[HTTPRequestManager defaultManager] HTTPGetRequestWithApiName:kHLRequestEditNotes parameters:params success:^(NSURLSessionDataTask * _Nonnull dataTask, id  _Nonnull responseObject){
        [MBProgressHUD hideHUD];
        if ([responseObject[@"code"] integerValue] == 200) {
            if ([responseObject[@"state"] isEqualToString:@"1"]) {
                [MBProgressHUD showSuccessMessage:@"删除成功"];
                
                /**** 重置 笔记创建 ****/
                [detailNodeView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
                [detailNodeView setUI];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nonnull dataTask, NSError * _Nonnull error) {
         [MBProgressHUD hideHUD];
        [MBProgressHUD showErrorMessage:@"网络超时"];
    }];
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (!decelerate) {
        [self scrollViewDidEndDecelerating:scrollView];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSInteger index = scrollView.contentOffset.x / ScreenWidth;
    UIButton *button = self.tabBarButtons[index];
    [self tabBarButtonClick:button];
}

#pragma mark - ZFPlayerDelegate

- (void)zf_playerBackAction {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)zf_playerDownload:(NSString *)url
{
}

- (void)zf_playerControlViewWillShow:(UIView *)controlView isFullscreen:(BOOL)fullscreen
{
}

- (void)zf_playerControlViewWillHidden:(UIView *)controlView isFullscreen:(BOOL)fullscreen
{
}

#pragma mark - HLDetailDiscussViewDelegate
- (void)detailDiscussView:(HLDetailDiscussView *)detailDiscussView didClickAskQuestion:(UIButton *)button
{
    HLStartQusetionViewController *start = [HLStartQusetionViewController new];
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:start];
    start.question_course_id = self.foldCourse.wkid;
    [self presentViewController:nav animated:YES completion:^{
        [self.playerView pause];
    }];
}

- (void)detailDiscussView:(HLDetailDiscussView *)detailDiscussView questionListDidSelecte:(HLCourseDiscuss *)course
{
    [self.playerView pause];
    HLCommentListController *comment = [HLCommentListController new];
    comment.courseDiscuss = course;
    [self.navigationController pushViewController:comment animated:YES];
}

#pragma mark - HLDetailNodeViewDelegate
- (void)detailNodeView:(HLDetailNodeView *)detailNodeView didClickCreteNote:(UIButton *)button
{
    HLCreateNoteController *createNote = [[HLCreateNoteController alloc] init];
    createNote.note_course_id = self.foldCourse.wkid;
    createNote.title = @"创建笔记";
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:createNote];
    createNote.noteCompletionBlock = ^(NSString *note){
        detailNodeView.note = note;
    };
    [self presentViewController:nav animated:YES completion:nil];
}

- (void)detailNodeView:(HLDetailNodeView *)detailNodeView editNote:(NSString *)note
{
    HLCreateNoteController *createNote = [[HLCreateNoteController alloc] init];
    createNote.title = @"编辑笔记";
    createNote.note_course_id = self.foldCourse.wkid;
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:createNote];
    createNote.note = note;
    createNote.noteCompletionBlock = ^(NSString *note){
        detailNodeView.note = note;
    };
    [self presentViewController:nav animated:YES completion:nil];
}

- (void)detailNodeView:(HLDetailNodeView *)detailNodeView deleteNote:(NSString *)note
{
    [self requestDeleteNote:note detailNodeView:detailNodeView];
}


#pragma mark - Control

- (void)userAskQuestionSuccess
{
    [self.discussView reloadData];
}

- (void)tabBarButtonClick:(UIButton*)button
{
    /**** 点击相同按钮 直接return ****/
    if (_currentSelectedTabBarButton == button) {
        return;
    }
    _currentSelectedTabBarButton.selected = NO;
     button.selected = YES;
    _currentSelectedTabBarButton = button;
    [self.contentScrollView setContentOffset:CGPointMake(ScreenWidth *button.tag, 0) animated:YES];
}


- (void)bottomButtonClick:(UIButton*)button
{
    switch (button.tag) {
        case HLBottomButtonTypeBack:{
            [self.navigationController popViewControllerAnimated:YES];
        }
            break;
            /****  收藏 ****/
        case HLBottomButtonTypeCollect:{
            [self collectedWith:button];
        }
            break;
            /**** 下载 ****/
        case HLBottomButtonTypeDownload:{
        
            [self addDataBaseCourseDetail];

        }
            break;
        default:
            break;
    }
}

- (void)addDataBaseCourseDetail
{
    if ([HLDataBaseManager isDownloadedFile:self.courseDetail] ) {
        [MBProgressHUD showSuccessMessage:@"已经下载完成"];
        return;
    }
    
    if ([HLDataBaseManager isDownloadingFile:self.courseDetail]) {
        [MBProgressHUD showSuccessMessage:@"已经加入下载队列"];
        return;
    }
    [MBProgressHUD showTipMessageInView:@"已加入下载列表"];
    
    __weak typeof(self)weakSelf = self;
    [[HLDownLoaderManager shareInstance]hl_downLoader:[NSURL URLWithString:self.courseDetail.play_url] downLoadInfo:^(long long totalSize) {
        self.courseDetail.totalSize = totalSize;
        if ([HLDataBaseManager isDownloadingFile:self.courseDetail]) {
            [HLDataBaseManager removeDownloadingFile:self.courseDetail];
        }
        [HLDataBaseManager addDownloadingFile:self.courseDetail];
        
        [[NSNotificationCenter defaultCenter]postNotificationName:kHLDownLoadTableViewReloadDataNotifacation object:nil];
        
    } progress:^(float progress) {
        
    } success:^(NSString *filePath) {
        /**** 强引用 ****/
        __strong typeof (weakSelf)strongSelf = weakSelf;
        strongSelf.courseDetail.filePath = filePath;
        //正在下载的数据库 删除记录
        if ([HLDataBaseManager isDownloadingFile:strongSelf.courseDetail]) {
            [HLDataBaseManager removeDownloadingFile:strongSelf.courseDetail];
        }
        //成功下载 加入成功表
        if ([HLDataBaseManager isDownloadedFile:strongSelf.courseDetail]) {
            [HLDataBaseManager removeDownloadedFile:strongSelf.courseDetail];
        }
        [HLDataBaseManager addDownloadedFile:strongSelf.courseDetail];
        
       [[NSNotificationCenter defaultCenter]postNotificationName:kHLDownLoadTableViewReloadDataNotifacation object:nil];
        
    } failed:^{
    }];
}


- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    NSLog(@"%@释放了",self.class);
}

@end
